public class Test1 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param board string字符串一维数组
     * @param word string字符串
     * @return bool布尔型
     */
    public static int[] x = {0,0,-1,1}, y = {1,-1,0,0};
    public static boolean[][] vis;
    public boolean exist (String[] board, String word) {
        // write code here
        int m = board.length;
        int n = board[0].length();
        char[][] s = new char[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                s[i][j] = board[i].charAt(j);
            }
        }
        vis = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (s[i][j] == word.charAt(0) && !vis[i][j]) {
                    if (dfs(s,word,i,j,1)) return true;
                }
            }
        }
        return false;
    }

    public static boolean dfs(char[][] s, String word, int a, int b,int p) {
        vis[a][b] = true;
        if (p == word.length()) return true;
        for (int i = 0; i < 4; i++) {
            int m = a + x[i], n = b + y[i];
            if (m >= 0 && m < s.length && n >= 0 && n < s[0].length && !vis[m][n]) {
                if (s[m][n] == word.charAt(p)) {
                    boolean ret = dfs(s,word,m,n,p + 1);
                    if (ret) return true;
                    vis[m][n] = false;
                }
            }
        }
        return false;
    }
}
